package com.novellotus.iov.carvice.model;

import android.Manifest;
import android.widget.Button;
import android.widget.EditText;

import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.novellotus.iov.carvice.R;
import com.novellotus.iov.carvice.activity.LoginActivity;
import com.novellotus.iov.carvice.activity.MainActivity;
import com.novellotus.iov.carvice.activity.MainActivityOld;
import com.novellotus.iov.carvice.bean.RxLoginBean;
import com.novellotus.iov.carvice.retrofit.BaseEntity;
import com.novellotus.iov.carvice.retrofit.BaseObserver;
import com.novellotus.iov.carvice.retrofit.RetrofitFactory;
import com.novellotus.iov.carvice.retrofit.RxSchedulers;
import com.novellotus.iov.carvice.rxjava.MyObserver;
import com.novellotus.iov.carvice.utils.MyUtils;
import com.novellotus.iov.carvice.utils.MyViewUtils;
import com.novellotus.iov.carvice.utils.SharedPreferencesUtils;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;

/**
 * Created by Rich on 2017/8/3.
 */

public class LoginModel {

    private LoginActivity context;
    private Observable<CharSequence> ObservablePhone;
    private Observable<CharSequence> ObservablePassword;

    public LoginModel(LoginActivity context) {
        this.context = context;
    }


    /**
     * 设置账号编辑框
     */
    public void setMobileEdit(final EditText mobile) {
        ObservablePhone = RxTextView.textChanges(mobile);
        ObservablePhone.compose(RxSchedulers.<CharSequence>lifecycle(context))
                .compose(RxSchedulers.<CharSequence>compose())
                .subscribe(new MyObserver<CharSequence>() {
                    @Override
                    public void onNext(CharSequence pass) {
                        super.onNext(pass);
                        if (MyUtils.isMobile(pass.toString()) || MyUtils.isEmail(pass.toString())) {
                            mobile.setTextColor(context.getResources().getColor(R.color.text_black));
                        } else {
                            mobile.setTextColor(context.getResources().getColor(R.color.textTipsRed));
                        }
                    }
                });
    }


    /**
     * 设置密码编辑框
     */
    public void setPasswordEdit(final EditText password) {
        ObservablePassword = RxTextView.textChanges(password);
        ObservablePassword.compose(RxSchedulers.<CharSequence>lifecycle(context))
                .compose(RxSchedulers.<CharSequence>compose())
                .subscribe(new MyObserver<CharSequence>() {
                    @Override
                    public void onNext(CharSequence pass) {
                        super.onNext(pass);
                        if (pass.length() >= 6) {
                            password.setTextColor(context.getResources().getColor(R.color.text_black));
                        } else {
                            password.setTextColor(context.getResources().getColor(R.color.textTipsRed));
                        }
                    }
                });
    }


    /**
     * 点击登陆按钮
     */
    public void clickLogin(Button btnLogin, final EditText username, final EditText password) {
        RxView.clicks(btnLogin).compose(RxSchedulers.lifecycle(context)).throttleFirst(3, TimeUnit.SECONDS).compose(context.rxPermissions.ensureEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                Observable<BaseEntity<RxLoginBean>> observable = RetrofitFactory.getInstance().login(username.getText().toString(), password.getText().toString());
                observable.compose(RxSchedulers.<BaseEntity<RxLoginBean>>compose())
                        .subscribe(new BaseObserver<RxLoginBean>(context) {
                            @Override
                            public void onSuccess(RxLoginBean rxJavaLoginBean) {
                                if (rxJavaLoginBean != null) {
                                    SharedPreferencesUtils.saveKey(rxJavaLoginBean.getKeys().getAccessKey(), rxJavaLoginBean.getKeys().getSecretKey(), rxJavaLoginBean.getId(), context);
                                    SharedPreferencesUtils.saveUser(rxJavaLoginBean.getId(), rxJavaLoginBean.getMobile(), rxJavaLoginBean.getEmail(), rxJavaLoginBean.getNickName(), context);
                                    context.openActivity(MainActivity.class);
                                    context.finish();
                                } else {
                                    MyUtils.showToast(context, "登录失败，请重新登录");
                                }

                            }

                            @Override
                            public void onFail(int code, String msg) {
                                MyUtils.showToast(context, msg);
                            }

                            @Override
                            public void onError(String msg) {
                                MyUtils.showToast(context, msg);
                            }

                        });
            }

        });
    }


    /**
     * 表单验证
     */
    public void setConfirm(final Button button) {
        Observable.combineLatest(ObservablePhone, ObservablePassword, new BiFunction<CharSequence, CharSequence, Boolean>() {
            @Override
            public Boolean apply(CharSequence phone, CharSequence password) throws Exception {
                return phone.length() > 10 && password.length() >= 6;
            }
        }).compose(RxSchedulers.<Boolean>lifecycle(context)).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean pass) throws Exception {
                if (pass) {
                    MyViewUtils.setButtonClickable(button, true);
                } else {
                    MyViewUtils.setButtonClickable(button, false);
                }
            }
        });
    }
}
